# @File    : cycle_ota.py
# @Project : JBL_Android&iOS
from poco.exceptions import PocoNoSuchNodeException
from common.logUtil import info_a, warning_a
from Android.upgrade import Upgrade
from airtest.core.api import *

from exception.custom_exception import ElectricException


class CycleOta(Upgrade):

    c_version = Upgrade.location['c_version']
    test_device = Upgrade.location['device']
    success = "更新成功.*"

    def cycle_ota(self, num):
        self.check_version()
        for i in range(1, int(num) + 1):
            try:
                start_time = time.time()
                if self.test_device == "耳机":
                    version = self.poco(textMatches=f"{self.earbud}").get_text()[5:]
                else:
                    version = self.poco(textMatches=f"{self.case}").get_text()[6:]
                self.page_back()
                self.select_version(version, self.test_device)
                self.ota_start(i, version)
                self.ota_process(i, version)
                end_time = time.time()
                total_time = end_time - start_time
                minutes, seconds = divmod(total_time, 60)
                info_a(f"第 {i} 次循环升级耗时: {int(minutes)} 分 {int(seconds)} 秒")
                sleep(2)
            except ElectricException:
                self.fail_num += 1
                self.fail_list.append(i)
                warning_a(f"第 {i} 次测试时耳机电量低于50%")
                break
            except PocoNoSuchNodeException:
                self.fail_num += 1
                self.fail_list.append(i)
                warning_a("未找到元素，请重新执行程序!")
                break
        sleep(2)
        info_a(f"测试完成, 共压测 {i} 次, 其中 PASS {self.pass_num} 次, FAIL {self.fail_num} 次, FAIL的轮数为{self.fail_list}")
        self.fail_list.clear()

    # 根据当前版本选择耳机升级版本
    def select_version(self, version, test_device):
        if version == self.c_version:
            self.poco(text=f"{self.location['cycle_version_package']}").click()
            if test_device == "耳机":
                self.poco(textMatches=f"{self.location['ota_package']}").click()
            elif test_device == "充电盒":
                self.poco(textMatches=f"{self.location['case_package']}").click()
        # 返回
        self.poco("jbl.stc.com.debug:id/image_view_back").click()

        self.poco("jbl.stc.com.debug:id/image_view_info_a_back").click()

    def ota_start(self, i, version):
        self.poco("android.widget.FrameLayout").offspring("jbl.stc.com.debug:id/grid_view_dashboard").child(
            "android.widget.LinearLayout")[0].offspring(
            "jbl.stc.com.debug:id/image_view_item_connected_before_device_icon").click()
        self.poco(text="Others").click()
        swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
        self.poco(text="支持").click()
        if self.test_device == "耳机":
            self.poco(text="软件").click()
        else:
            self.poco(text="智能保护盒").click()
        # self.poco(text="更新").refresh()
        self.poco(text="更新").click()
        if version == self.c_version:
            info_a(f"第 {i} 次循环升级开始...")

    def ota_process(self, i, version):
        while True:
            if self.poco(textMatches=f"{self.schedule}").exists():
                while True:
                    if self.poco(text="耳机电量需超过 50%。").exists():
                        raise ElectricException
                    if not self.poco(textMatches=f"{self.schedule}").exists():
                        if self.poco(textMatches=f"{self.success}").exists():
                            self.poco(text="完成").click()
                            if self.test_device == "耳机":
                                version = self.poco(textMatches=f"{self.earbud}").get_text()[5:]
                            elif self.test_device == "充电盒":
                                version = self.poco(textMatches=f"{self.case}").get_text()[6:]
                            self.check_after_version(i, version)
                            break
                        # 更新失败处理
                        elif self.poco(text="更新失败").exists():
                            self.poco(text="取消").click()
                            sleep(2)
                            version = self.ex.check_fail()
                            self.check_after_version(i, version)
                            self.fail_num += 1
                            self.fail_list.append(i)
                            break
                        elif self.poco(text="General").exists():
                            self.poco(text="Others").click()
                            swipe((self.width * 0.5, self.height * 0.88), (self.width * 0.5, self.height * 0.6))
                            self.poco(text="支持").click()
                            if self.test_device == "耳机":
                                version = self.poco(textMatches=f"{self.earbud}").get_text()[5:]
                            elif self.test_device == "充电盒":
                                version = self.poco(textMatches=f"{self.case}").get_text()[6:]
                            self.check_after_version(i, version)
                            break
                break
            if self.poco(text="重试").exists():
                warning_a("请将充电盒靠近手机后重试")
                self.poco(text="重试").click()
                sleep(1)
                self.poco(text="更新").click()

    # 根据升级后的版本来进行后续操作
    def check_after_version(self, i, version):
        if version == self.c_version:
            info_a(f"当前充电盒版本: {version}")
            sleep(1)
            stop_app("jbl.stc.com.debug")
            time.sleep(2)
            start_app("jbl.stc.com.debug")
            v = self.check_version()
            while True:
                if v == version:
                    info_a(f"第 {i} 次循环升级成功...")
                    sleep(2)
                    info_a(f"第 {i} 次循环升级后的版本为: {version}")
                    sleep(2)
                    self.pass_num += 1
                    break
                else:
                    warning_a(f"当前充电盒版本: {v}")
                    sleep(1)
                    stop_app("jbl.stc.com.debug")
                    time.sleep(2)
                    start_app("jbl.stc.com.debug")
                    v = self.check_version()


